package com.aircms.controller.admin;

import com.aircms.common.ServerResponse;
import com.aircms.controller.BaseAdminController;
import com.aircms.pojo.Permission;
import com.aircms.pojo.validation.BaseQueryFieldsValidation;
import com.aircms.service.IPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;

import java.util.List;
import java.util.Map;

/**
 * @author air
 * @create 2018-06-28 下午2:54
 */
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@RestController
@RequestMapping(value = "api/admin/auth/permission")
public class PermissionAdminController extends BaseAdminController {
    @Autowired
    private IPermissionService iPermissionService;

    /**
     * Display a listing of the resource.
     *
     * @return
     */
    @GetMapping(value = "")
    public ServerResponse index() throws Exception {
        try {
            return ServerResponse.response(iPermissionService.index());
        } catch (Exception e) {
            this.errorLog(this.getClass(), e);
            throw new Exception("查询失败");
        }
    }


    /**
     * Store a newly created resource in storage.
     * 注意： 这里只是同步路由权限，不和菜单权限挂钩
     *
     * @return
     */
    @PostMapping(value = "")
    @Transactional
    public ServerResponse store() throws Exception {
        try {
            // 获取所有路由
            Map map = getAllRoutes();

            // 先删除已经废弃的路由
            ServerResponse route = iPermissionService.getAllRoutes();

            List<Permission> permissions = (List<Permission>) route.getData();

            permissions.forEach(item -> {
                final int[]  mark={0};
                map.forEach((k, v) -> {
                    RequestMappingInfo requestMappingInfo = (RequestMappingInfo) k;
                    String url = requestMappingInfo.getPatternsCondition().toString()
                            .substring(1, requestMappingInfo.getPatternsCondition().toString().length() - 1);
                    String method = requestMappingInfo.getMethodsCondition().toString()
                            .substring(1, requestMappingInfo.getMethodsCondition().toString().length() - 1);

                    if(item.getUrl().equals(url)&&item.getMethod().equals(method)){ //
                       mark[0]=1;
                    }

                    // 这里频繁读取数据库了,
//                    iPermissionService.store(url, method);
                });

                if(mark[0]==0){  // 删除已经不存在的路由
                    try {
                        this.destroy(item.getId());
                    } catch (Exception e) {
                        this.errorLog(this.getClass(), e);
                    }
                }
            });


            map.forEach((k, v) -> {
                RequestMappingInfo requestMappingInfo = (RequestMappingInfo) k;
                String url = requestMappingInfo.getPatternsCondition().toString()
                        .substring(1, requestMappingInfo.getPatternsCondition().toString().length() - 1);
                String method = requestMappingInfo.getMethodsCondition().toString()
                        .substring(1, requestMappingInfo.getMethodsCondition().toString().length() - 1);
                iPermissionService.store(url, method);
            });

            return ServerResponse.response();
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            this.errorLog(this.getClass(), e);
            throw new Exception("同步失败");
        }

    }


    /**
     * Display the specified resource.
     *
     * @param id
     * @return
     */
    @GetMapping(value = "{id}")
    public ServerResponse show(@PathVariable Integer id) {

        return ServerResponse.response();
    }


    /**
     * Update the specified resource in storage.
     *
     * @return
     */
    @RequestMapping(value = "{id}", method = {RequestMethod.PUT, RequestMethod.PATCH})
    public ServerResponse update(@PathVariable Integer id, Permission permission) throws Exception {
        try {
            return iPermissionService.update(permission);
        } catch (Exception e) {
            this.errorLog(this.getClass(), e);
            throw new Exception("更新失败");
        }

    }


    /**
     * Remove the specified resource from storage.
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "{id}")
    public ServerResponse destroy(@PathVariable Integer id) throws Exception {
        try {
            return iPermissionService.destroy(id);
        } catch (Exception e) {
            this.errorLog(this.getClass(), e);
            throw new Exception("删除失败");
        }
    }


    @PostMapping(value = "menuStore")
    public ServerResponse menuStore(@Validated Permission permission, BindingResult bindingResult) throws Exception {
        try {
            if (bindingResult.hasErrors()) { // 表单验证
                return ServerResponse.response("", -800, bindingResult.getFieldError().getDefaultMessage());
            }
            return iPermissionService.insertMenuPermission(permission);

        } catch (Exception e) {
            this.errorLog(this.getClass(), e);
            throw new Exception("添加菜单失败");
        }
    }

    @GetMapping(value = "menuIndex")
    public ServerResponse menuIndex(BaseQueryFieldsValidation baseQueryFields) throws Exception {
        try {
            return iPermissionService.getMenuPermission(baseQueryFields, getPageNum(), getPageSize());
        } catch (Exception e) {
            this.errorLog(this.getClass(), e);
            throw new Exception("查询失败");
        }
    }

    @GetMapping(value = "routerIndex")
    public ServerResponse routerIndex(BaseQueryFieldsValidation baseQueryFields) throws Exception {
        try {
            return iPermissionService.getRouterPermission(baseQueryFields, getPageNum(), getPageSize());
        } catch (Exception e) {
            this.errorLog(this.getClass(), e);
            throw new Exception("查询失败");
        }
    }

    @GetMapping(value = "getAllRoute")
    public ServerResponse getAllRoute(Integer roleId) throws Exception {
        try {
            return iPermissionService.getAllRoutes(roleId);
        } catch (Exception e) {
            this.errorLog(this.getClass(), e);
            throw new Exception("查询失败");
        }
    }

    /**
     * 获取所有菜单，并返回当前角色拥有菜单，并标记
     * @param roleId
     * @return
     * @throws Exception
     */
    @GetMapping(value = "getAllMenu")
    public ServerResponse getAllMenu(Integer roleId) throws Exception {
        try {
            return iPermissionService.getAllMenu(roleId);
        } catch (Exception e) {
            this.errorLog(this.getClass(), e);
            throw new Exception("查询失败");
        }
    }


}
